import { createStore, Store } from 'vuex'
import type { InjectionKey } from 'vue'
import type { UserInfo } from '@/api/user'

// 为 store state 声明类型
export interface State {
  token: string | null;
  userInfo: UserInfo | null;
}

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()

// 创建 store 实例
export const store = createStore<State>({
  state: {
    token: localStorage.getItem('admin-token'),
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')!) : null
  },
  mutations: {
    SET_TOKEN(state, token: string) {
      console.log('设置token:', token)
      state.token = token
      localStorage.setItem('admin-token', token)
    },
    SET_USER_INFO(state, userInfo: UserInfo) {
      console.log('设置用户信息:', userInfo)
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    CLEAR_USER_STATE(state) {
      console.log('清除用户状态')
      state.token = null
      state.userInfo = null
      localStorage.removeItem('admin-token')
      localStorage.removeItem('userInfo')
    }
  },
  getters: {
    isAuthenticated: (state) => {
      const authenticated = !!state.token
      console.log('认证状态检查:', authenticated)
      return authenticated
    },
    userInfo: (state) => {
      console.log('获取用户信息:', state.userInfo)
      return state.userInfo
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore(): Store<State> {
  return store
}

export default store 